<template>
  <div class="body">
    <div class="middle">
      <div class="bg" style="padding: 40px 0">
        <transition name="el-zoom-in-top">
          <img v-show="shows" src="~@/assets/bg.png" alt="" />
        </transition>
      </div>
      <div class="inputBox">
        <el-input
          v-model="keyWord"
          type="text"
          placeholder="请输入文本"
          x-webkit-speech
        >
          <img src="~@/assets/麦克风.svg" alt="" class="mkf" slot="prepend" />
          <div
            class="myButton"
            slot="append"
            @mousedown="enterInput()"
            ref="btnRef"
          >
            <!-- <img src="~@/assets/button.png" alt="" class="mkf" /> -->
          </div>
        </el-input>
        <div
          style="
            height: 100px;
            width: 300px;
            border: 1px solid #ccc;
            box-sizing: border-box;
            display: inline-block;
            vertical-align: bottom;
            position: absolute;
            top: -50%;
            z-index: 9999999;
            right: 18%;
            opacity: 0;
            background: #fff;
          "
          class="ctrlProcessWave"
          ref="LineBox"
        ></div>
      </div>
      <ul class="tablesBox" v-loading="loadtable">
        <!-- v-if="item.list.length !== 0"  -->
        <li v-for="(item, index) in dataList" @click="getTable(item)">
          <div class="title" v-if="titleShow">
            <span>{{ item.title }}</span>
          </div>
          <template>
            <div class="sql" v-if="sqlShow">{{ item.sql }}</div>
            <!-- <div class="progress" v-if="item.list.length !== 0"> -->
            <div class="progress" v-if="titleShow">
              <el-progress
                :percentage="item.percentage"
                v-if="titleShow"
              ></el-progress>
            </div>
            <!-- <div class="progress" v-if="retDesc !== '运行SQL异常'">
              <el-progress :percentage="item.percentage" v-if="retDesc !== '运行SQL异常'"></el-progress>
            </div> -->
            <!-- <div v-if="item.list.length !== 0"> -->
            <div>
              <div class="tables" v-show="countNum === undefined">
                <el-table
                  :data="item.list"
                  style="width: 100%"
                  max-height="300"
                  ref="table"
                  :header-cell-style="{
                    background: 'rgba(242,242,242)',
                  }"
                  v-loading="loadings"
                >
                  <el-table-column
                    v-for="items in item.header"
                    :prop="items.columnName"
                    :label="
                      items.columnComment
                        ? items.columnComment
                        : items.columnName
                    "
                    width="width"
                  >
                  </el-table-column>  
                </el-table>
              </div>
              <!-- v-if="item.list.length !== 0" 之前是判断item.sql.length长度，接口变化了，换成用sql判断 -->
              <div
                class="tables"
                v-show="countNum !== undefined"
                v-if="item.sql.length !== 0"
              >
                <!-- <div class="tables" v-show="countNum !== undefined" v-if="retDesc === '运行SQL异常'"> -->
                <el-table
                  :data="dataListTow"
                  style="width: 100%"
                  max-height="300"
                  ref="table"
                  :header-cell-style="{
                    background: 'rgba(242,242,242)',
                  }"
                  v-loading="loadings"
                >
                  <el-table-column prop="columnNum" label="数量" width="width">
                  </el-table-column>
                </el-table> 
              </div>
            </div>
            <!-- <div v-if="item.header.length !== 0">
              <div class="tables" v-show="countNum === undefined">
                <el-table
                  :data="item.list"
                  style="width: 100%"
                  max-height="300"
                  ref="table"
                  :header-cell-style="{
                    background: 'rgba(242,242,242)',
                  }"
                  v-loading="loadings"
                >
                  <el-table-column
                    v-for="items in item.header"
                    :prop="items.columnName"
                    :label="
                      items.columnComment
                        ? items.columnComment
                        : items.columnName
                    "
                    width="width"
                  >
                  </el-table-column>
                </el-table>
              </div>
            </div> -->
          </template>
        </li>
      </ul>
      <!--  -->
      <div class="tips">
        <h3>使用须知：</h3>
        <p>
          一、用户信息宽表中，可以查询性别、地市、终端宽带、办理福包、近一个月活跃的itv、开通翼支付、宽带当月是否活跃、电话号码、4G套餐、终端零售价、套餐下itv个数、副卡、ITV数量、连续沉默天数、在网月份数、年龄(青年；中年；老年)、视频偏好、是否欠费、费用等级、近三月短信次数、流量使用记录、流量饱和度、流量包个数、家庭WIFI异网号码、翼支付消费次数、互联网盒子、参加0元加副卡政策、翼支付月消费次数、近三个月月均itv使用时长、游戏偏好、网购偏好、音乐偏好、有车一族、家有老人、家有青少年、家有小孩、智能组网、换机目标、
        </p>
        <p>
          二、外呼表中，可以查询活动号、失败原因(具体原因需要在原因的第一位和最后一位加上$符号)
        </p>
      </div>
    </div>
    <!-- <canvas id="wave" type="2d" class="canvas"></canvas> -->
  </div>
</template>

<script>
/********加载RecordApp需要用到的支持文件*********/
//必须引入的app核心文件，换成require也是一样的。注意：app.js会自动往window下挂载名称为RecordApp对象，全局可调用window.RecordApp，也许可自行调整相关源码清除全局污染
import RecordApp from "recorder-core/src/app-support/app";
//可选开启Native支持，需要引入此文件
import "recorder-core/src/app-support/app-native-support";
//可选开启IOS上微信录音支持，需要引入此文件
import "recorder-core/src/app-support/app-ios-weixin-support";

/*********加载Recorder需要的文件***********/
//必须引入的核心，所有需要的文件都应当引入，引入后会检测到组件已自动加载
//不引入也可以，app.js会去用script动态加载，应确保app.js内BaseFolder目录的正确性(参阅RecordAppBaseFolder)，否则会导致404 js加载失败
import Recorder from "recorder-core";

//【要打包到一个js就解开注释】本demo是通过script动态引入这些引擎js文件
//需要使用到的音频格式编码引擎的js文件统统加载进来，这些引擎文件会比较大
//【解开】import 'recorder-core/src/engine/mp3'
//【解开】import 'recorder-core/src/engine/mp3-engine'
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
import "recorder-core/src/engine/wav";
// import "recorder-core/src/engine/wav-engine";
//由于大部分情况下ios-weixin的支持需要用到amr解码器，应当把amr引擎也加载进来，这些引擎文件会比较大
//【解开】import 'recorder-core/src/engine/beta-amr'
//【解开】import 'recorder-core/src/engine/beta-amr-engine'
//【解开】import 'recorder-core/src/engine/wav' //amr依赖了wav引擎

//可选的扩展支持项
import "recorder-core/src/extensions/waveview";
import axios from "axios";
import request from "@/untils/request1";
export default {
  name: "Index",
  data() {
    return {
      // 在用户信息宽表中查找对游戏偏好不高的用户信息
      keyWord: "",
      shows: true,
      loadings: false,
      countNum: null, //判断count(*)字段是否存在
      titleShow: false, //控制标题和sql的显隐
      sqlShow: false,
      dataListTow: [], //有
      dataList: [
        {
          title: "",
          sql: "",
          list: [],
          header: [],
          percentage: 10,
          timer: null,
        },
      ],
      loadtable: false,
      retDesc: "",
      // 下面的变量与录音相关
      App: RecordApp,
      Rec: Recorder,
      type: "wav",
      bitRate: 16,
      sampleRate: 16000,
      rec: false,
      duration: 0,
      powerLevel: 0,
      recOpenDialogShow: 0,
      logs: [],
      timer: null,
      sendMsg: false,
    };
  },
  mounted() {
    // this.recReq();
    // let btnRef = this.$refs.btnRef;
    // console.log(btnRef);
    // btnRef.addEventListener("mouseup", () => {
    //   console.log("我松开了");
    //   this.sendMsg = true;
    //   this.recStop();
    //   let LineBox = this.$refs.LineBox;
    //   LineBox.style.opacity = "0";
    // });
  },
  methods: {
    // 点击搜索
    enterInput() {
      console.log("我按下了");
      setTimeout(() => {
        // 判断600毫秒内按钮有没有被松开
        // if (this.sendMsg) {
        console.log("我该去发信息了");
        this.sendMsgs();
        this.sendMsg = false;
        // } else {
        //   console.log("我该去录音了");
        //   let LineBox = this.$refs.LineBox;
        //   LineBox.style.opacity = "1";
        // this.recStart();
        // }
      }, 600);
      return;
    },
    // 发送信息
    sendMsgs() {
      if (!this.keyWord) return this.$message.error("输入信息不可为空");
      this.shows = false;
      this.loadings = true;
      this.titleShow = false;
      this.sqlShow = false;
      this.loadtable = true;
      (this.countNum = null), 
      (this.dataListTow = []);
      this.retDesc = "";
      this.dataList[0].percentage = 20;
      // this.getTable(this.dataList[0]);
      // const loading = this.$loading({
      //   lock: true,
      //   text: "Loading",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      // this.recReq();
      request({
        url: "voiceData/getResultByText",
        type: "get",
        data: { text: this.keyWord },
      }).then(({ data }) => {
        console.log(data);

        if (data.retCode === "000000" && data.result) {
          this.getTable(this.dataList[0]);
          this.titleShow = true;
          this.sqlShow = true;
          console.log("======this.titleShow=", this.titleShow);
          let { resultKv, sqlStr, tableFields } = data.result;
          // if (resultKv.length !== 0) {
          if (resultKv === null) {
            console.log("1111111111111111");
            // this.countNum = resultKv[0]["count(*)"];
            this.countNum = null;
          } else {
            this.countNum = undefined;
            console.log("222222222222222222");
            this.dataList[0].header = tableFields;
          }
          console.log("data.result==", data.result);
          console.log("countNum==", this.countNum);

          if (sqlStr) {
            this.dataList[0].sql = sqlStr;
            this.getTableList(data.result.id);
          } else {
            this.dataList[0].sql = "";
          }
          //接口返回形式改变了，resultKv为null，这里获取不了，无法控制上面两个表格的显隐，
          //这里的接口获取sql 调取下面的接口 在下面的接口获取以下的值

          //判断resultKv[0]数量是否存在
          // if (this.countNum !== undefined) {
          //   console.log("resultKv[0]==", resultKv[0]);
          //   for (var key in resultKv[0]) {
          //     let obj = {};
          //     console.log(
          //       "key名称是：" + key + ",key的值是：" + resultKv[0][key]
          //     );
          //     obj.columnNmae = "数量";
          //     obj.columnNum = resultKv[0][key];
          //     this.dataListTow.push(obj);
          //     console.log("=this.dataList[0].header", this.dataListTow);
          //   }
          // }
          // if (resultKv) {
          //   this.dataList[0].list = resultKv;
          // } else {
          //   this.dataList[0].list = [];
          // }
          // if (tableFields) {
          //   this.dataList[0].header = tableFields;
          // } else {
          //   this.dataList[0].header = [];
          // }
          this.dataList[0].title = this.keyWord;
          // this.dataList[0].sql = sqlStr;
          console.log("this.dataList===", this.dataList);
          this.dataList[0].percentage = 100;
          this.loadtable = false;
          // loading.close();
          // this.dataList[0].list = resultKv;
          // this.dataList[0].header = tableFields;
        } else {
          console.log("data===", data);
          console.log("this.dataList===", this.dataList);
          // this.dataList[0] = {}
          // this.dataList.length = 0
          // this.dataList[0].percentage = 10
          this.dataList[0].title = "";
          this.dataList[0].sql = "";
          // this.dataList[0].timer = null
          this.dataList[0].list = [];
          console.log("this.dataList[0].list===", this.dataList[0].list);
          console.log("this.dataList[0]===", this.dataList[0]);
          this.countNum = null;
          console.log("======this.countNum", this.countNum);
          this.loadtable = false;
          this.$message.error(data.retDesc);
          // this.titleShow = true;
          this.sqlShow = true;
          this.retDesc = data.retDesc;
          this.dataList[0].sql = data.result.split(",")[1];
          console.log("this.dataList[0].sql=", this.dataList[0].sql);
        }
      });
      this.loadings = false;
    },
    //获取表格数据
    getTableList(id) {
      console.log("id====", id);
      // return
      request({
        url: "voiceData/getResultBySql",
        type: "get",
        data: { id: id },
      }).then(({ data }) => {
        if (data.retCode === "000000" && data.result) {
          // this.countNum = null
          console.log("this.countNumthis.countNumthis.countNumthis.countNum==",this.countNum);
          console.log("data====",data);
          // let { resultKv } = data.result;
          let { resultKv, sqlStr, tableFields } = data.result;
          if (resultKv.length !== 0) {
          // if (resultKv === null) {
            console.log("1111111111111111");
            this.countNum = resultKv[0]["count(*)"];
            // this.countNum = null;
          } else {
            this.countNum = undefined;
            console.log("222222222222222222");
            this.dataList[0].header = tableFields;
          }
          if (resultKv) {
            this.dataList[0].list = resultKv;
          } else {
            this.dataList[0].list = [];
          }
          if (tableFields) {
            this.dataList[0].header = tableFields;
          } else {
            this.dataList[0].header = [];
          }
          console.log("resultKv[0]==", resultKv[0]);
            for (var key in resultKv[0]) {
              let obj = {};
              console.log(
                "key名称是：" + key + ",key的值是：" + resultKv[0][key]
              );
              obj.columnNmae = "数量";
              obj.columnNum = resultKv[0][key];
              this.dataListTow.push(obj);
              console.log("=this.dataList[0].header", this.dataListTow);
            }
        }
      });
    },

    // 点击title
    getTable(item) {
      console.log("item==", item);
      item.timer = setInterval(() => {
        this.plus(item);
      }, 1000);
    },
    // 每秒++
    plus(item) {
      if (item.percentage > 94) {
        clearInterval(item.timer);
        item.timer = null;
      } else {
        //进度条随机增长1-5
        item.percentage += Math.floor(Math.random() * 5) + 1;
      }
    },
    // 请求权限
    recReq() {
      this.rec = false;
      //   this.dialogInt = setTimeout(function () {
      //定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
      // this.showDialog();
      //   }, 8000);
      RecordApp.RequestPermission(
        () => {
          this.rec = true;
          //   this.dialogCancel();

          this.reclog("已打开录音，可以点击录制开始录音了", 2);
        },
        function (err, isUserNotAllow) {
          //   this.dialogCancel();
          this.reclog(
            (isUserNotAllow ? "UserNotAllow，" : "") + "打开录音失败：" + err,
            1
          );
        }
      );
      this.waitDialogClickFn = function () {
        // this.dialogCancel();
        this.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗", 1);
      };
    },
    // 开始录制
    recStart: function () {
      var This = this;
      if (!This.rec || !RecordApp.Current) {
        console.log(This.rec, RecordApp.Current);
        This.reclog("未请求权限", 1);
        return;
      }

      if (RecordApp.Current == RecordApp.Platforms.Weixin) {
        This.reclog("正在使用微信JsSDK，录音过程中不会有任何回调，不要惊慌");
      } else if (RecordApp.Current == RecordApp.Platforms.Native) {
        This.reclog("正在使用Native录音，底层由App原生层提供支持");
      } else {
        This.reclog("正在使用H5录音，底层由Recorder直接提供支持");
      }

      var set = {
        type: This.type,
        bitRate: This.bitRate,
        sampleRate: This.sampleRate,
        onProcess: function (buffers, powerLevel, duration, sampleRate) {
          This.duration = duration;
          This.powerLevel = powerLevel;

          This.wave.input(buffers[buffers.length - 1], powerLevel, sampleRate);
        },
      };

      RecordApp.Start(
        set,
        function () {
          This.reclog(
            RecordApp.Current.Key +
              "录制中:" +
              set.type +
              " " +
              set.bitRate +
              "kbps",
            2
          );

          //此处创建这些音频可视化图形绘制浏览器支持妥妥的
          This.wave = Recorder.WaveView({ elem: ".ctrlProcessWave" });
        },
        function (err) {
          This.reclog(RecordApp.Current.Key + "开始录音失败：" + err, 1);
        }
      );
    },
    // 停止录制
    recStop: function () {
      // if (this.sendMsg) return;
      var This = this;
      var rec = This.rec;
      This.rec = false;

      if (!rec || !RecordApp.Current) {
        This.reclog("未请求权限", 1);
        return;
      }

      RecordApp.Stop(
        function (blob, duration) {
          This.reclog("已录制:", "", {
            blob: blob,
            duration: duration,
            rec: RecordApp.GetStopUsedRec(),
          });
          This.downLoad(blob);
          This.uoLoad(blob);
          This.recReq();
        },
        function (msg) {
          This.reclog("录音失败：" + msg, 1);
        }
      );
    },
    // 下载
    downLoad(blob) {
      console.log("调用了下载方法");
      let aLink = document.createElement("a");
      aLink.href = URL.createObjectURL(blob);
      aLink.setAttribute("download", "qwe.wav"); // 设置下载文件名称
      document.body.appendChild(aLink);
      aLink.click();
      URL.revokeObjectURL(aLink.href); //释放url
      document.body.appendChild(aLink);
    },
    // 上传
    uoLoad(blob) {
      let file = new window.File([blob], "123.wav", {
        type: "audio/wav",
        lastModified: Date.now(),
      });
      console.log(file);
      let paramsData = new FormData();
      paramsData.append(`file`, file);
      console.log(axios);
      axios({
        url: "http://134.64.248.185:8666/zhijian/zhijianlink/getBlobToWav",
        method: "POST",
        data: paramsData,
        headers: { "Content-Type": "multipart/form-data" },
      }).then(({ data }) => {
        console.log("res", data);
        this.keyWord = this.doData(data.data);
        this.sendMsgs();
      });
    },
    // 打印
    reclog(str, color, res) {
      console.log(str);
      this.$message(str);
    },
    // 处理数据
    doData(str) {
      let temp = str.split("\\")[0];
      console.log(temp.lastIndexOf("data"));
      let newTemp = temp.slice(temp.lastIndexOf("data"));
      console.log("newTemp", newTemp.slice(8, -4));
      let script = newTemp.slice(8, -4);
      let tempArr1 = script.split(",");
      let tempArr = [];
      console.log(tempArr1);
      // 把空数据找到并删除
      if (tempArr1.length !== 0) {
        tempArr1.forEach((item, index) => {
          if (item.trim() == "") {
            // KongArr.push(index);
            tempArr1.splice(index, 1);
          }
        });
      }
      // 把字符串的数据转换成对象
      for (let i = 0; i < tempArr1.length; i += 3) {
        try {
          let obj = {};
          obj.lid = tempArr1[i].split(":")[1];
          obj.spk = tempArr1[i + 1].split(":")[1];
          console.log(obj.spk);
          obj.onebest = tempArr1[i + 2].split(":")[1].replace("]", "");
          tempArr.push(obj);
        } catch (error) {
          console.log(error);
        }
      }
      let nerStr = "";
      if (Array.isArray(tempArr)) {
        tempArr.forEach((item) => {
          nerStr += item.onebest.replace(/。/, "");
        });
      }
      console.log("tempArr", tempArr);
      console.log("nerStr", nerStr);
      return nerStr;
    },
  },
};
</script>

<style scoped>
.body {
  width: 100vw;
  height: 100vh;
  /* background: #000; */
  overflow: auto;
}
.middle {
  width: 1200px;
  margin: 0 auto;
}
.middle > .bg {
  width: 100%;
  text-align: center;
}
.middle > .bg > img {
  width: 400px;
}
.middle > .inputBox {
  position: relative;
  margin: 0 auto;
  width: 70%;
  border: 1px solid rgb(155, 206, 255);
  border-radius: 30px;
  /* overflow: hidden; */
  padding: 3px 0px;
  /* display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center; */
}
.mkf {
  margin-top: 3px;
}

.myButton {
  padding: 8px 26px;
  border-radius: 18px;
  /* background-image: linear-gradient(
    to top,
    rgba(1, 86, 207, 1),
    rgba(1, 128, 253, 0.9)
  ); */
  cursor: pointer;
  background: url("@/assets/button.png") no-repeat;
  height: 20px;
  width: 50px;
  background-size: cover;
  box-shadow: 0px 2px 3px 3px #ccc;
  transition: all 0.2s;
}
.myButton:active {
  box-shadow: 0px 0px 0px 0px #ccc;
}
.tips {
  width: 70%;
  margin: 20px auto;
  padding: 20px;
  box-sizing: border-box;
  border: 1px dashed rgb(72, 165, 255);
  border-radius: 18px;
  line-height: 1.5;
  font-size: 14px;
  font-family: "Arial Normal", "Arial", sans-serif;
  font-weight: 400;
}
.tips > h3 {
  font-size: 18px;
}
.tablesBox {
  position: relative;
  width: 70%;
  margin: 0 auto;
  padding-left: 20px;
}
.tablesBox li {
  position: relative;
  padding: 20px 0;
}
.tablesBox li .title {
  position: relative;
  font-size: 15px;
  font-family: "Arial Normal", "Arial", sans-serif;
  font-weight: 400;
  line-height: 40px;
  cursor: pointer;
}
.tablesBox li .title span {
  margin-left: 60px;
}
.tablesBox li .title::before {
  content: "";
  position: absolute;
  width: 40px;
  height: 40px;
  background: url("@/assets/search.png") no-repeat;
  background-size: cover;
}
.tablesBox li .sql {
  margin: 20px 0;
  /* padding: 15px 2px 2px 17px; */
  box-sizing: border-box;
  /* height: 89px; */
  border-radius: 10px;
  font-size: 18px;
  padding: 20px;
  background: inherit;
  background-color: rgba(242, 245, 247, 0.988235294117647);
  font-family: "Arial Normal", "Arial", sans-serif;
  font-weight: 400;
  font-style: normal;
  /* font-size: 13px; */
  letter-spacing: normal;
  color: #333333;
}
.tables {
  box-sizing: border-box;
  padding: 10px;
  margin: 20px 0 0px 0;
  border: 1px dashed rgb(72, 165, 255);
  border-radius: 10px;
  overflow: auto;
}
/deep/.el-input-group__append,
/deep/.el-input-group__prepend {
  background-color: transparent !important;
  border: 0px solid #ccc !important;
  /* text-align: center !important; */
}
/deep/.el-input__inner {
  background-color: transparent !important;
  border: 0px solid #ccc !important;
}
/* .wave {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 9999;
  width: 100vw;
  height: 100px;
  overflow: hidden;
}
.canvas {
  width: 100vw;
  height: 100px;
} */
</style>